from typing import List, Optional
from ..interfaces import PlatformAdapter, NormalizedContent
from ..vendor.mindspider.media_platform.kuaishou.client import KuaishouClient


class KuaishouAdapter(PlatformAdapter):
    def __init__(self, headers: Optional[dict] = None, proxy: Optional[str] = None):
        self.client = KuaishouClient(headers=headers or {}, proxy=proxy)

    async def search_by_keywords(self, keywords: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for kw in keywords:
            data = await self.client.search_by_keyword(kw, page=1)
            vsp = data.get('visionSearchPhoto') or {}
            arr = vsp.get('feeds') or []
            for it in arr:
                photo = it.get('photo') or {}
                vid = str(photo.get('id') or '')
                title = photo.get('caption') or ''
                desc = photo.get('originCaption') or ''
                author = (it.get('author') or {}).get('name')
                url = photo.get('photoUrl') or None
                items.append(NormalizedContent(platform='kuaishou', content_id=vid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=photo))
        return items

    async def fetch_by_accounts(self, accounts: List[str], time_start: Optional[str], time_end: Optional[str]) -> List[NormalizedContent]:
        items: List[NormalizedContent] = []
        for uid in accounts:
            data = await self.client.get_user_videos(uid, cursor=0)
            vlist = data.get('visionProfilePhotoList') or {}
            arr = vlist.get('feeds') or []
            for it in arr:
                photo = it.get('photo') or {}
                vid = str(photo.get('id') or '')
                title = photo.get('caption') or ''
                desc = photo.get('originCaption') or ''
                author = (it.get('author') or {}).get('name')
                url = photo.get('photoUrl') or None
                items.append(NormalizedContent(platform='kuaishou', content_id=vid, author=author, title=title, text=desc, url=url, published_at=None, metrics={}, raw=photo))
        return items
